package com.feinno.module.security.web;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;

import com.feinno.framework.common.web.AbstractController;
import com.feinno.module.security.domain.Role;
import com.feinno.module.security.domain.User;
import com.feinno.module.security.service.RoleService;
import com.feinno.module.security.service.UserService;
import com.google.common.collect.Maps;

@Controller
@RequestMapping(value = "/admin/system/user")
public class UserController extends AbstractController<User, UserService> {

	private static Map<String, String> allUserTypes = Maps.newTreeMap();
	private static Map<String, String> allStatus = Maps.newTreeMap();
	static {
		allUserTypes.put("1", "管理员");
		allUserTypes.put("2", "操作员");

		allStatus.put("1", "有效");
		allStatus.put("2", "无效");
	}

	@SuppressWarnings("unused")
	@Autowired
	private UserService userService;
	@Autowired
	private RoleService roleService;

	@RequestMapping(value = "changePassword")
	public String forwardChangePasswordView(@ModelAttribute("loadEntity") User entity, Model model) {
		model.addAttribute(getEntityName(), entity);
		return "/admin/system/userChangePassword";
	}

	@RequestMapping(value = "saveChangePassword")
	public String changePassword(@ModelAttribute("loadEntity") User entity, Model model, HttpServletRequest request,
			HttpServletResponse response) {
		String orginalPassword = request.getParameter("password");
		String newPassword = request.getParameter("newPassword");

		if (entity != null) {
			boolean result = getEntityService().validatePassword(entity, orginalPassword);
			if (result) {
				getEntityService().changePassword(entity, newPassword);
				saveMessage(request, "密码修改成功");
			} else {
				saveMessage(request, "原始密码错误");
			}
		} else {
			saveMessage(request, "没有改用户存在");
		}

		return getSuccessView();
	}

	@Override
	protected void onCreate(Model model, HttpServletRequest request, HttpServletResponse response) {
		super.onCreate(model, request, response);
		appendRoleData(model, request);
	}

	@Override
	protected void onEdit(User entity, Model model, HttpServletRequest request, HttpServletResponse response) {
		super.onEdit(entity, model, request, response);
		appendRoleData(model, request);
	}

	@Override
	protected void onSave(User entity, Model model, HttpServletRequest request, HttpServletResponse response,
			boolean isCreate) {
		entity.setRoles(loadRoleFormRequest(request));
		if (isCreate) {
			getEntityService().createUser(entity);
		} else {
			User orgUser = getEntityService().get(entity.getId());
			if (StringUtils.isNotBlank(entity.getName())) {
				orgUser.setName(entity.getName());
			}
			if (StringUtils.isNotBlank(entity.getStatus())) {
				orgUser.setStatus(entity.getStatus());
			}
			if (StringUtils.isNotBlank(entity.getEmail())) {
				orgUser.setEmail(entity.getEmail());
			}
			if (StringUtils.isNotBlank(entity.getUserType())) {
				orgUser.setUserType(entity.getUserType());
			}
			getEntityService().update(orgUser);
		}
	}

	@Override
	protected void referenceData(HttpServletRequest request, Map<String, Object> model) {
		model.put("allStatus", allStatus);
		model.put("allUserTypes", allUserTypes);
	}

	/**
	 * 不自动绑定对象中的roleList属性，另行处理。
	 */

	private void appendRoleData(Model model, HttpServletRequest request) {
		List<Role> list = roleService.getAll();
		request.setAttribute("totalRows", list.size());
		model.addAttribute("rolelist", list);
	}

	@InitBinder
	@Override
	public void initBinder(WebDataBinder binder) {
		binder.setDisallowedFields("roles");
		super.initBinder(binder);
	}

	private Set<Role> loadRoleFormRequest(HttpServletRequest request) {
		String roleStr = request.getParameter("role");
		roleStr = roleStr.substring(0, roleStr.length() - 1);
		String[] roleArray = roleStr.split("\\|");
		List<String> rolelist = new ArrayList<String>();
		for (int i = 0; i < roleArray.length; i++) {
			rolelist.add(roleArray[i]);
		}
		Set<Role> roles = new HashSet<Role>();
		for (String roleid : rolelist) {
			Role role = roleService.get(Long.valueOf(roleid));
			roles.add(role);
		}
		return roles;
	}

}
